package com.moon.ws;

import com.moon.entity.Admin;
import com.moon.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@Component
public class WsInterceptor implements HandshakeInterceptor {
    @Autowired
    private AdminService adminService;
    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
        ServletServerHttpRequest servletServerHttpRequest = (ServletServerHttpRequest) request;
        HttpServletRequest req = servletServerHttpRequest.getServletRequest();
        Admin adm = (Admin) req.getSession().getAttribute("admin");
        Admin admin = adminService.selectById(adm.getId());
        attributes.put("admin", admin);
        return true;//false  握手失败  被拦截
    }

    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {
        System.out.println("握手成功!!!");
    }
}
